#include "InputProcessor.h"
#include "KeyCode.h"
#include "CVector2.h"
#include "IWareDevice.h"

#define KEYDOWN(code) ((GetAsyncKeyState(code) & 0x8000) ? 1 : 0)
#define KEYUP(code)   ((GetAsyncKeyState(code) & 0x8000) ? 0 : 1)

void InputProcessor::Update()
{
	ProcessMouse();
}
//----------------------------------------------------------------------------------
void InputProcessor::ProcessMouse()
{
	static VBOOL s_bLButtonDown = VFALSE;
	static VBOOL s_bRButtonDown = VFALSE;
	static VBOOL s_bLRButtonDown = VFALSE;

	if( KEYDOWN(KEY_RBUTTON) && KEYDOWN(KEY_LBUTTON) )
	{
		if( !s_bLRButtonDown )
		{
			InputMessageParam param;
			BuildMouseParam( param );
			Invoke( IE_MOUSE_LRBUTTONDOWN, param );
		}

		s_bLButtonDown = VTRUE;
		s_bRButtonDown = VTRUE;
		s_bLRButtonDown = VTRUE;
		return;
	}

	if( ( KEYUP(KEY_RBUTTON) || KEYUP(KEY_LBUTTON) ) && s_bLRButtonDown )
	{
		InputMessageParam param;
		BuildMouseParam( param );
		Invoke( IE_MOUSE_LRBUTTONUP, param );

		if( KEYUP(KEY_RBUTTON) )
			s_bRButtonDown = VFALSE;

		if( KEYUP(KEY_LBUTTON) )
			s_bLButtonDown = VFALSE;

		s_bLRButtonDown = VFALSE;
		return;
	}

	if( KEYDOWN(KEY_LBUTTON) && !s_bLRButtonDown && !s_bLButtonDown )
	{
		InputMessageParam param;
		BuildMouseParam( param );
		Invoke( IE_MOUSE_LBUTTONDOWN, param );
		s_bLButtonDown = VTRUE;
	}

	if( KEYDOWN(KEY_RBUTTON) && !s_bLRButtonDown && !s_bRButtonDown )
	{
		InputMessageParam param;
		BuildMouseParam( param );
		Invoke( IE_MOUSE_RBUTTONDOWN, param );
		s_bRButtonDown = VTRUE;
	}

	if( KEYUP(KEY_LBUTTON) && s_bLButtonDown )
	{
		InputMessageParam param;
		BuildMouseParam( param );
		Invoke( IE_MOUSE_LBUTTONUP, param );
		s_bLButtonDown = VFALSE;
	}

	if( KEYUP(KEY_RBUTTON) && s_bRButtonDown )
	{
		InputMessageParam param;
		BuildMouseParam( param );
		Invoke( IE_MOUSE_RBUTTONUP, param );
		s_bRButtonDown = VFALSE;
	}
}
//----------------------------------------------------------------------------------
void InputProcessor::BuildMouseParam( InputMessageParam& param )
{
	param.bAlt = KEYDOWN( KEY_LMENU ) || KEYDOWN( KEY_RMENU );
	param.bCtrl = KEYDOWN( KEY_LCONTROL ) || KEYDOWN( KEY_RCONTROL );
	param.bShift = KEYDOWN( KEY_LSHIFT ) || KEYDOWN( KEY_RSHIFT );
	if( m_pWareDevice )
	{
		WareCommon::CVector2 pos;
		m_pWareDevice->GetMousePos( pos );
		param.uParam1 = static_cast<int32>(pos[0]);
		param.uParam2 = static_cast<int32>(pos[1]);
	}
	else
	{
		param.uParam1 = 0;
		param.uParam2 = 0;
	}
}